package com.yiwei.ydd.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yiwei.ydd.R;
import com.yiwei.ydd.api.Api;
import com.yiwei.ydd.api.bean.OilcardAgencyCreateBean;
import com.yiwei.ydd.api.bean.PagesDetailBean;
import com.yiwei.ydd.api.bean.UploadImgBean;
import com.yiwei.ydd.base.BaseActivity;
import com.yiwei.ydd.constant.Const;
import com.yiwei.ydd.constant.IdCardBitmap;
import com.yiwei.ydd.constant.UserInfoGlobal;
import com.yiwei.ydd.util.ImageUtil;
import com.yiwei.ydd.util.Network;
import com.yiwei.ydd.util.RxLifeUtil;
import com.yiwei.ydd.util.ToastUtil;
import com.yiwei.ydd.util.UI;
import com.yiwei.ydd.view.PagesDetailDialog;
import com.yiwei.ydd.view.SelectAreaDilaog;
import com.yiwei.ydd.view.V19FrameLayout;
import com.lljjcoder.citypickerview.widget.CityPicker;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class OilAgencyActivity extends BaseActivity implements SelectAreaDilaog.OnChooseListener {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.edit_name)
    EditText editName;
    @BindView(R.id.txt_province)
    TextView txtProvince;
    @BindView(R.id.txt_city)
    TextView txtCity;
    @BindView(R.id.txt_area)
    TextView txtArea;
    @BindView(R.id.edit_address)
    EditText editAddress;
    @BindView(R.id.img_idcard_front)
    ImageView imgIdcardFront;
    @BindView(R.id.img_idcard_back)
    ImageView imgIdcardBack;
    @BindView(R.id.txt_money)
    TextView txtMoney;
    @BindView(R.id.txt_tips)
    TextView txtTips;
    @BindView(R.id.btn_agree_check)
    ImageView btnAgreeCheck;
    @BindView(R.id.txt_service_shihua)
    TextView txtServiceShihua;
    @BindView(R.id.txt_service_app)
    TextView txtServiceApp;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    private static final String DEFAULT_NAME1 = "front_image.jpg";
    private static final String DEFAULT_NAME2 = "back_image.jpg";
    private Unbinder unbiner;
    //    private CityPicker cityPicker;
    private int takeType;
    private boolean isAgree = false;
    private SelectAreaDilaog selectAreaDialog;

    private OilcardAgencyCreateBean submitBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_oil_agency);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        submitBean = new OilcardAgencyCreateBean();
        txtTitle.setText("代办油卡");
        txtRight.setText("常见问题");
        txtRight.setVisibility(View.VISIBLE);
        selectAreaDialog = new SelectAreaDilaog(this).setOnChooseListener(this);
    }

    @OnTextChanged({R.id.edit_phone, R.id.edit_name, R.id.edit_address})
    void afterTextChanged(Editable s) {
        if (TextUtils.isEmpty(UI.toString(editPhone)) || TextUtils.isEmpty(UI.toString(editName)) || TextUtils.isEmpty(UI.toString(editAddress))) {
            btnSubmit.setSelected(false);
        } else {
            if (!isAgree || TextUtils.isEmpty(submitBean.province_id) || TextUtils.isEmpty(submitBean.idcard_back_path) || TextUtils.isEmpty(submitBean.idcard_path)) {
                btnSubmit.setSelected(false);
            } else {
                btnSubmit.setSelected(true);
            }
        }
    }

    private void setBtnSelect() {
        if (!isAgree || TextUtils.isEmpty(UI.toString(editAddress)) || TextUtils.isEmpty(UI.toString(editName)) || TextUtils.isEmpty(UI.toString(editPhone)) || TextUtils.isEmpty(submitBean.province_id) || TextUtils.isEmpty(submitBean.idcard_back_path) || TextUtils.isEmpty(submitBean.idcard_path)) {
            btnSubmit.setSelected(false);
        } else {
            btnSubmit.setSelected(true);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == -1) {
                try {

                    if (takeType == 1) {
                        if (IdCardBitmap.bitmap != null) {
                            getUploadImage(IdCardBitmap.bitmap);
//                            imgIdcardFront.setImageBitmap(IdCardBitmap.bitmap);
                        }
                    } else if (takeType == 2) {

                        if (IdCardBitmap.bitmap != null) {
                            getUploadImage(IdCardBitmap.bitmap);
//                            imgIdcardBack.setImageBitmap(IdCardBitmap.bitmap);
                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void startTakePhoto(int type) {
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                takeType = type;
                if (type == 1) {
                    startActivity(DEFAULT_NAME1);
                } else if (type == 2) {
                    startActivity(DEFAULT_NAME2);
                }
            }
        }, R.string.camera_storage_card_p, R.string.get_cammra, android.Manifest.permission.CAMERA, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    private void startActivity(String paramString) {
        Intent localIntent = new Intent(this, CameraActivity.class);
        localIntent.putExtra("path", "/sdcard/pictures");
        localIntent.putExtra("name", paramString);
        localIntent.putExtra("type", "idcard");
        startActivityForResult(localIntent, 100);
    }

    public void getUploadImage(Bitmap bitmap) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
        loadingDialog.show();
        UploadImgBean bean = new UploadImgBean();
        bean.img = ImageUtil.Bitmap2StrByBase64(bitmap, 100);
        Api.api_service.getUploadImage(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (takeType == 1) {
                        Glide.with(this).load(result.datas.url).into(imgIdcardFront);
                        submitBean.idcard_path = result.datas.url;
                        setBtnSelect();
                    } else {
                        Glide.with(this).load(result.datas.url).into(imgIdcardBack);
                        submitBean.idcard_back_path = result.datas.url;
                        setBtnSelect();
                    }
                });
    }

    public void getPagesDetail() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }
       loadingDialog.show();
        PagesDetailBean item = new PagesDetailBean();
        item.keyword = Const.PageDetailType.APP_SERVICE;
        Api.api_service.getPagesDetail(item).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                     loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    Intent intent1 = new Intent(this, WebViewActivity.class);
                    intent1.putExtra("content", result.datas.content);
                    intent1.putExtra("title", result.datas.title);
                    this.startActivity(intent1);
                });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (IdCardBitmap.bitmap != null) {
            IdCardBitmap.bitmap.recycle();
            IdCardBitmap.bitmap = null;
        }
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.txt_right, R.id.btn_back, R.id.txt_province, R.id.txt_city, R.id.txt_area, R.id.img_idcard_front, R.id.img_idcard_back, R.id.btn_agree_check, R.id.txt_service_shihua, R.id.txt_service_app, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_right:
                Intent intent2 = new Intent(this, WebViewActivity.class);
                intent2.putExtra("url", UserInfoGlobal.getQuestions());
                intent2.putExtra("title", "常见问题");
                startActivity(intent2);
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.txt_province:
                selectAreaDialog.show();
//                cityPicker.show();
                break;
            case R.id.txt_city:
                selectAreaDialog.show();
//                cityPicker.show();
                break;
            case R.id.txt_area:
                selectAreaDialog.show();
//                cityPicker.show();
                break;
            case R.id.img_idcard_front:
                startTakePhoto(1);
                break;
            case R.id.img_idcard_back:
                startTakePhoto(2);
                break;
            case R.id.btn_agree_check:
                isAgree = !isAgree;
                if (!isAgree) {
                    btnAgreeCheck.setImageResource(R.mipmap.img_oil_agree_uncheck);
                } else {
                    btnAgreeCheck.setImageResource(R.mipmap.img_oil_agree_check);
                }
                setBtnSelect();
                break;
            case R.id.txt_service_shihua:
                new PagesDetailDialog(this).setKeyword(Const.PageDetailType.SINOPEC_SERVICE).show();
                break;
            case R.id.txt_service_app:
                getPagesDetail();
//                new PagesDetailDialog(this).setKeyword(Const.PageDetailType.APP_SERVICE).show();
                break;
            case R.id.btn_submit:
                if (TextUtils.isEmpty(UI.toString(editPhone))) {
                    ToastUtil.makeText(this, "手机号不能为空");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(editName))) {
                    ToastUtil.makeText(this, "姓名不能为空");
                    return;
                }
                if (TextUtils.isEmpty(submitBean.province_id)) {
                    ToastUtil.makeText(this, "省市区不能为空");
                    return;
                }
                if (TextUtils.isEmpty(submitBean.idcard_path)) {
                    ToastUtil.makeText(this, "身份证正面不能为空");
                    return;
                }
                if (TextUtils.isEmpty(submitBean.idcard_back_path)) {
                    ToastUtil.makeText(this, "身份证反面不能为空");
                    return;
                }
                if (!isAgree) {
                    ToastUtil.makeText(this, "请勾选同意协议");
                    return;
                }
                submitBean.mobile = UI.toString(editPhone);
                submitBean.username = UI.toString(editName);
                submitBean.area_detail = UI.toString(editAddress);

                Intent intent = new Intent(this, VipOrderPayMoneyActivity.class);
                intent.putExtra("agency", submitBean);
                intent.putExtra("pay_money", "30");
                startActivity(intent);
                overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
        }
    }

    
    
    @Override
    public void onAddressSelect(String provinceId, String provinceName, String cityId, String cityName, String areaId, String areaName) {

        submitBean.province_id = provinceId;
        submitBean.city_id = cityId;
        submitBean.area_id = areaId;
        if (TextUtils.isEmpty(provinceName)) {
            provinceName = "";
        }
        if (TextUtils.isEmpty(cityName)) {
            cityName = "";
        }
        if (TextUtils.isEmpty(areaName)) {
            areaName = "";
        }
        txtProvince.setText(provinceName);
        txtCity.setText(cityName);
        txtArea.setText(areaName);
    }
}
